package com.xing.algorithm.string;

/**
 * 字符串专注整数
 */
public class MyAtoi {
    public static int myAtoi(String str) {
        if(str == null) {
            return 0;
        }

        int i = 0;
        int sum = 0;
        boolean sign = false;
        while(i < str.length() && str.charAt(i) == ' ') {
            i ++;
        }

        if(i < str.length()) {
            if(str.charAt(i) == '-') {
                sign = true;
                i++;
            }else if(str.charAt(i) == '+') {
                i++;
            }
        }

        while(i < str.length()) {
            char ch = str.charAt(i);
            if(ch < '0' || ch > '9') {
                break;
            }

            if (sum > Integer.MAX_VALUE / 10 || (sum == Integer.MAX_VALUE / 10 && (str.charAt(i) - '0') > Integer.MAX_VALUE % 10)) {
                return sign? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            sum = sum * 10 + (str.charAt(i) - '0');
            i++;

        }

        return sign?-sum:sum;

    }
    public static void main(String[] args) {
        System.out.println(myAtoi("   -+42"));
    }
}
